package com.zhushenwudi.openblock.slice;

import com.orhanobut.logger.Logger;
import com.zhushenwudi.openblock.MyApplication;
import com.zhushenwudi.openblock.ResourceTable;
import com.zhushenwudi.openblock.utils.Toast;
import net.grandcentrix.tray.AppPreferences;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.webengine.BrowserAgent;
import ohos.agp.components.webengine.WebView;
import ohos.bundle.AbilityInfo;
import ohos.data.distributed.common.*;
import ohos.data.distributed.device.DeviceFilterStrategy;
import ohos.data.distributed.device.DeviceInfo;
import ohos.data.distributed.user.SingleKvStore;

import java.util.ArrayList;
import java.util.List;

public class MainAbilitySlice extends AbilitySlice {

    private final AppPreferences sp = MyApplication.getInstance().getSp();
    private String xe;
    private KvManager kvManager;
    private SingleKvStore singleKvStore;
    private WebView webView;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        boolean isTablet = ohos.system.DeviceInfo.getDeviceType().equals("tablet");
        if (isTablet) setDisplayOrientation(AbilityInfo.DisplayOrientation.LANDSCAPE);
        super.setUIContent(ResourceTable.Layout_ability_main);

        initDbManager();

        webView = (WebView) findComponentById(ResourceTable.Id_webview);
        webView.setEnabled(true);
        webView.setBrowserAgent(new BrowserAgent(getContext()));
        webView.getWebConfig().setJavaScriptPermit(true);
        webView.addJsCallback("test", s -> {
            sp.put("xe", s);
            xe = s;
            if (xe == null) {
                Toast.myToast(getContext(), "数据异常");
                return "data error";
            }
            syncData();
            return "receive ok";
        });
        final String url = "http://192.168.100.239:9080/frontpage/index.html";

        webView.load(url);
    }

    private void initDbManager() {
        kvManager = createManager();
        singleKvStore = createDb(kvManager);
        subscribeDb(singleKvStore);
    }

    private KvManager createManager() {
        KvManager manager = null;
        try {
            KvManagerConfig config = new KvManagerConfig(getContext());
            manager = KvManagerFactory.getInstance().createKvManager(config);
        } catch (KvStoreException exception) {
            Logger.e("aaa", exception.getKvStoreErrorCode());
        }
        return manager;
    }

    private SingleKvStore createDb(KvManager manager) {
        SingleKvStore kvStore = null;
        try {
            Options options = new Options();
            options.setCreateIfMissing(true).setEncrypt(false).setKvStoreType(KvStoreType.SINGLE_VERSION);
            kvStore = manager.getKvStore(options, "xe");
        } catch (KvStoreException exception) {
            Logger.e("aaa", exception.getKvStoreErrorCode());
        }
        return kvStore;
    }

    private void subscribeDb(SingleKvStore kvStore) {
        KvStoreObserver kvStoreObserverClient = new KvStoreObserverClient();
        kvStore.subscribe(SubscribeType.SUBSCRIBE_TYPE_REMOTE, kvStoreObserverClient);
    }

    private void syncData() {
        List<DeviceInfo> deviceInfoList = kvManager.getConnectedDevicesInfo(DeviceFilterStrategy.NO_FILTER);
        List<String> deviceIdList = new ArrayList<>(0);
        for (DeviceInfo deviceInfo : deviceInfoList) {
            deviceIdList.add(deviceInfo.getId());
        }
        if (deviceIdList.size() == 0) {
            Toast.myToast(getContext(), "组网失败");
            return;
        }
        singleKvStore.registerSyncCallback(map -> {
            getUITaskDispatcher().asyncDispatch(() -> Toast.myToast(getContext(), "请在手机端进行预览"));
            singleKvStore.unRegisterSyncCallback();
        });
        singleKvStore.putString("xe", xe);
        singleKvStore.sync(deviceIdList, SyncMode.PUSH_PULL);
    }

    @Override
    protected void onStop() {
        kvManager.closeKvStore(singleKvStore);
        super.onStop();
    }

    private class KvStoreObserverClient implements KvStoreObserver {
        @Override
        public void onChange(ChangeNotification notification) {
            for (Entry entry : notification.getUpdateEntries()) {
                boolean isXe = "xe".equals(entry.getKey());
                if (entry.getKey() != null && isXe) {
                    String jsContent = "javascript:callJS('" + entry.getValue().getString() + "')";
                    getUITaskDispatcher().asyncDispatch(() -> webView.executeJs(jsContent, null));
                }
            }
        }
    }
}
